import {
	defineStore
} from 'pinia';
import {
	get
} from '/hooks/req.js'
//创建store管理用户信息
export const useUserStore = defineStore('user', {
	state: () => {
		return {
			userInfo: {
				id: '',
				nickName: '',
				avatarUrl: '',
				token: '',
			}

		}
	},

});
export const useUserAddressStore = defineStore('address', {
	state: () => {
		return {
			AddressList: []
		}
	},
	actions: {
		//加载用户地址信息
		loadAddressList() {
			let userStore = useUserStore()
			if (!userStore.userInfo.id) return
			get("/address/user/" + userStore.userInfo.id, uni.getStorageSync("token")).then(res => {
				if (res.data.status == 500) {
					uni.showToast({
						title: res.data.message,
						icon: "none"
					})
					userStore.$reset()
					this.AddressList=[]
					uni.removeStorage({
						key: "user"
					})
					uni.removeStorage({
						key: "token"
					})
				} else {
					if (res.data.data == "您还没有添加地址") {
						this.AddressList = []
					} else {
						this.AddressList = res.data.data
						const selectedIndex = this.AddressList.findIndex(item => item.isDefault == 0);
						this.AddressList.unshift(this.AddressList.splice(selectedIndex, 1)[0]);
					}
				}

			}).catch(err => {
				console.log(err);
			})
		},
		getAddressIsDefault() {
			return this.AddressList.findIndex(item => item.isDefault == 0);
		},
	}

});
export const useCart = defineStore('shoppingcart', {
	state: () => {
		return {
			//登录用户的购物车信息
			shoppingcartList: []
		}
	},
	actions: {
		//加载购物车信息
		loadShoppingcartList() {
			let userStore = useUserStore()
			if (!userStore.userInfo.id) return
			get("/cart/list/" + userStore.userInfo.id, uni.getStorageSync("token")).then(res => {
				if (res.data.status == 500) {
					uni.showToast({
						title: res.data.message,
						icon: "none"
					})
					this.shoppingcartList=[]
					userStore.$reset()
					uni.removeStorage({
						key: "user"
					})
					uni.removeStorage({
						key: "token"
					})
				} else {
					this.shoppingcartList = (res.data.data || []).map(r => {
						return {
							...r,
							state: false
						}
					})
				}
			}).catch(err => {
				console.log(err);
			})
		},
		delShoppingcartOne(id) {
			let index = this.shoppingcartList.findIndex(r => r.cart_id === id)
			this.shoppingcartList.splice(index, 1)
		},
		getShoppingcartQuantity() {
			return this.shoppingcartList.reduce((curr, prev) => curr + prev.quantity, 0)
		},
		clear() {
			this.shoppingcartList = []
		}
	}
})